﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace Bepo.Ext
{
    public static class HttpResponseExt
    {
        public static void CacheHard(this HttpResponse response)
        {

#if (!DEBUG)

            TimeSpan freshness = new TimeSpan(30, 0, 0, 0, 0);
            response.Cache.SetMaxAge(freshness);
            response.Cache.SetExpires(DateTime.UtcNow.Add(freshness));
            response.Cache.SetCacheability(HttpCacheability.Public);
            response.Cache.SetLastModified(DateTime.UtcNow.Add(new TimeSpan(-30, 0, 0, 0, 0)));
            response.Cache.SetValidUntilExpires(true);
#endif

        }

        public static void WriteCompressed(this HttpContext context, string text, string contentType)
        {
            byte[] buffer = null;
#if (!DEBUG)

            // COMPRESSION
            var encodingTypes = context.Request.Headers["Accept-Encoding"];
            string compressionType = "none";
            if (!string.IsNullOrEmpty(encodingTypes))
            {
                encodingTypes = encodingTypes.ToLower();
                if (context.Request.Browser.Browser == "IE")
                {
                    if (context.Request.Browser.MajorVersion < 6) compressionType = "none";
                    else if (
                        context.Request.Browser.MajorVersion == 6
                        && !string.IsNullOrEmpty(context.Request.ServerVariables["HTTP_USER_AGENT"])
                        && context.Request.ServerVariables["HTTP_USER_AGENT"].Contains("EV1"))
                        compressionType = "none";
                }
                if ((encodingTypes.Contains("gzip") || encodingTypes.Contains("x-gzip") || encodingTypes.Contains("*")))
                    compressionType = "gzip";
                else if (encodingTypes.Contains("deflate")) compressionType = "deflate";
            }

            if (compressionType == "gzip")
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    using (StreamWriter writer = new StreamWriter(new GZipStream(stream, CompressionMode.Compress), Encoding.UTF8))
                    {
                        writer.Write(text);
                    }
                    buffer = stream.ToArray();
                    context.Response.AddHeader("Content-encoding", "gzip");
                }
            }
            else if (compressionType == "deflate")
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    using (StreamWriter writer = new StreamWriter(new DeflateStream(stream, CompressionMode.Compress), Encoding.UTF8))
                    {
                        writer.Write(text);
                    }
                    buffer = stream.ToArray();
                    context.Response.AddHeader("Content-encoding", "deflate");
                }
            }
            else
            {
#endif
                buffer = context.Request.ContentEncoding.GetBytes(text);
                context.Response.ContentEncoding = context.Request.ContentEncoding;
#if (!DEBUG)
            }
#endif

            context.Response.ContentType = contentType;
            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            context.Response.AppendHeader("Content-Length", buffer.Length.ToString());
            context.Response.CacheHard();

            context.Response.Flush();

        }
    }
}